package com.huawei.chengdu.meetingdemo.view.dialogs;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.device.idea.meeting.MeetingCallback;
import com.huawei.chengdu.meetingdemo.R;
import com.huawei.chengdu.meetingdemo.consts.DialogConst;
import com.huawei.chengdu.meetingdemo.consts.ObserverConts;
import com.huawei.chengdu.meetingdemo.presenter.ConfSdkPresenter;
import com.huawei.chengdu.meetingdemo.util.LogUtil;
import com.huawei.chengdu.meetingdemo.util.StringUtil;
import com.huawei.chengdu.meetingdemo.presenter.MeetingManager;

import java.util.function.Consumer;

/**
 * Author: xurui 30031276
 * Created on 2022/10/9 15:22
 * Desc：
 */
public class AdvApplyHostView extends BaseView {
    private static final String TAG = "AdvApplyHostView";

    //输入密码
    private LinearLayout llPassword;
    //已是主席
    private TextView tvText;
    //密码错误提示
    private TextView tvPasswordError;
    //释放主席
    private TextView confirmSettingTv;
    //取消
    private TextView cancelSettingTv;
    //编辑密码
    private EditText etPassword;
    //申请主席标题
    private TextView tvMecharTitle;
    //清除密码
    private View clearPassword;

    private Runnable onDialogDismissEvent;

    private Consumer<String> onUpdateParentItemEvent;

    private String explain = "";

    private String fromView = "";


    public AdvApplyHostView(Context mContext) {
        super(mContext);
        initView();
    }

    public void setExplain(String explain) {
        this.explain = explain;
    }

    public void setFromView(String fromView) {
        this.fromView = fromView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.adv_apply_host;
    }


    private void initView() {
        if (mRootView == null) {
            LogUtil.error("initView error, mRootView is null");
            return;
        }
        tvText = mRootView.findViewById(R.id.tv_text);
        tvMecharTitle = mRootView.findViewById(R.id.set_white_board);
        tvPasswordError = mRootView.findViewById(R.id.tv_password_error);
        cancelSettingTv = mRootView.findViewById(R.id.cancel_setting_tv);
        cancelSettingTv.setOnClickListener(view -> setDialogDismiss());
        llPassword = mRootView.findViewById(R.id.ll_password);
        etPassword = mRootView.findViewById(R.id.et_password);
        tvText.setVisibility(View.VISIBLE);
        llPassword.setVisibility(View.GONE);
        initConfirmBth();
        setSaveBtnEnable(true);

        updateViewStatus(MeetingManager.getInstance().isMeChairman(),
                MeetingManager.getInstance().isHasChairman(), true);

        View eyeIcon = mRootView.findViewById(R.id.icon_eye);
        eyeIcon.setOnClickListener(view -> showOrHideaCodeAgain(view));
        registerListenerService();
    }

    private void showOrHideaCodeAgain(View eyeIcon) {
        if ("hide".equals(etPassword.getTag())) {
            etPassword.setTag("show");
            etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            eyeIcon.setBackgroundResource(R.drawable.visible_icon);
        } else {
            etPassword.setTag("hide");
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            eyeIcon.setBackgroundResource(R.drawable.invisible_icon);
        }
        etPassword.setSelection(etPassword.getText().length());
    }

    private void setDialogDismiss() {
        if (onDialogDismissEvent != null) {
            onDialogDismissEvent.run();
        }
    }

    private void initConfirmBth() {
        clearPassword = mRootView.findViewById(R.id.advance_password_clear);
        clearPassword.setOnClickListener(view -> clearPassword());
        confirmSettingTv = mRootView.findViewById(R.id.confirm_setting_tv);
        confirmSettingTv.setOnClickListener(this::applyOrReleaseHostChair);
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int before, int count) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (llPassword.getVisibility() == View.GONE) {
                    return;
                }
                char[] psdEditContent = etPassword.getText().toString().trim().toCharArray();
                setSaveBtnEnable(false);
                if (tvPasswordError.getVisibility() == View.VISIBLE) {
                    tvPasswordError.setVisibility(View.GONE);
                }
                if (psdEditContent.length > 0) {
                    setSaveBtnEnable(true);
                    clearPassword.setVisibility(View.VISIBLE);
                } else {
                    clearPassword.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
    }

    /**
     * 清除密码
     */
    private void clearPassword() {
        if (etPassword != null) {
            etPassword.setText("");
        }
    }

    /**
     * 申请或者释放主席
     */
    private void applyOrReleaseHostChair(View view) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(mContext.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }

        if (llPassword.getVisibility() == View.VISIBLE) { // 输入申请主席密码
            applyHostChair();
        } else if (ConfSdkPresenter.isChairman()) { // 本地是主席
            // 释放主席时，添加二次确认对话框
            Log.d(TAG, " applyOrReleaseHostChair : isMeChair");
            releaseHostChairDialog();
        } else if (ConfSdkPresenter.isHasChairman()) { // 本地不是主席但会议中有主席
            Log.d(TAG, " applyOrReleaseHostChair : isHasChair");
            String hostName = String.format(
                    mContext.getResources().getString(R.string.adv_host_other_chair_text),
                    ConfSdkPresenter.getHostName());
            updateToast(hostName);
        }
    }

    /**
     * 探测无密码申请主席，如果成功就走申请主席成功的逻辑，如果失败就继续提示输入密码
     */
    private void tryApplyChairWithoutPwd() {
        char[] numTxt = new char[]{};
        ConfSdkPresenter.applyChairmanAuthority(pwCharToString(numTxt),
                new MeetingCallback<Integer>() {
                    @Override
                    public void onSuccess(Integer succMsg) {
                        Log.d(TAG, "tryApplyChairWithoutPwd applyChairmanAuthority onSuccess");
                        updateViewStatus(ConfSdkPresenter.isChairman(), ConfSdkPresenter.isHasChairman(), false);
                        updateToast(R.string.conf_control_message_reqChair_success);
                    }

                    @Override
                    public void onFailed(int errCode, String errMsg) {
                        Log.d(TAG, "tryApplyChairWithoutPwd applyChairmanAuthority onFailed");
                        showInputView();
                    }
                });
    }

    /**
     * 显示输入密_码的界面，异步回调，需要进入主线程更新界面。
     */
    private void showInputView() {
        Log.d(TAG, "showInputView");
        new Handler(Looper.getMainLooper()).post(() -> {
            Log.d(TAG, "showInputView run()");
            llPassword.setVisibility(View.VISIBLE);
            tvText.setVisibility(View.GONE);
            clearPassword();
        });
    }

    private void setSaveBtnEnable(Boolean isEnable) {
        confirmSettingTv.setEnabled(isEnable);
        if (isEnable) {
            confirmSettingTv.setBackgroundResource(R.drawable.quite_button_bg);
        } else {
            confirmSettingTv.setBackgroundResource(R.drawable.quite_button_unenable);
        }
        confirmSettingTv.setTextColor(mContext.getColor(R.color.white));
    }

    private void applyHostChair() {
        char[] numTxt = etPassword.getText() == null
                ? new char[]{}
                : etPassword.getText().toString().trim().toCharArray();
        LogUtil.info("applyOrReleaseHostChair==: " + pwCharToString(numTxt));

        // 检测密_码长度
        if (numTxt.length == 0) {
            tryApplyChairWithoutPwd();
            tvPasswordError.setVisibility(View.VISIBLE);
            tvPasswordError.setText(mContext.getString(R.string.password_empty));
            return;
        }

        // 长度 不能超过 32位
        if (numTxt.length > 32 || StringUtil.getBytes(numTxt).length > 32) {
            tvPasswordError.setVisibility(View.VISIBLE);
            tvPasswordError.setText(mContext.getString(R.string.pwd_max_6_length));
            StringUtil.clearChars(numTxt);
            return;
        }

        if (!isCharsAllNumber(numTxt)) {
            tvPasswordError.setVisibility(View.VISIBLE);
            tvPasswordError.setText(mContext.getString(R.string.pwd_number_only_permit_hint));
            StringUtil.clearChars(numTxt);
            return;
        }

        Log.d(TAG, " applyOrReleaseHostChair : Apply Chair.");
        tvPasswordError.setVisibility(View.GONE);
        sendPwApplyChair(numTxt);
        StringUtil.clearChars(numTxt);
    }

    /**
     * 判断是否全是数字号码
     *
     * @param chars 字符串
     * @return 是否全是数字号码
     */
    private static boolean isCharsAllNumber(char[] chars) {
        for (int i = chars.length; --i >= 0; ) {
            if (!Character.isDigit(chars[i])) {
                return false;
            }
        }
        return true;
    }

    private void sendPwApplyChair(char[] numTxt) {
        ConfSdkPresenter.applyChairmanAuthority(pwCharToString(numTxt),
                new MeetingCallback<Integer>() {
                    @Override
                    public void onSuccess(Integer succMsg) {
                        LogUtil.info("applyChairmanAuthority onSuccess");
                        updateViewStatus(ConfSdkPresenter.isChairman(), ConfSdkPresenter.isHasChairman(), false);
                        updateToast(R.string.conf_control_message_reqChair_success);
                    }

                    @Override
                    public void onFailed(int errCode, String errMsg) {
                        LogUtil.info("applyChairmanAuthority onFailed==" + errCode + " ~~~ " + errMsg);
                        updateViewStatus(ConfSdkPresenter.isChairman(), ConfSdkPresenter.isHasChairman(), false);
                        updateToast(R.string.conf_control_message_reqChair_fail);
                    }
                });
    }

    private String pwCharToString(char[] chrCharArray) {
        return String.valueOf(chrCharArray);
    }

    private void updateViewStatus(boolean isMeChair, boolean isHasChair, boolean isInit) {
        new Handler(Looper.getMainLooper()).post(() -> {
            if (mContext == null) {
                return;
            }
            // 本地为主席
            if (isMeChair) {
                if (!isInit) {
                    updateParentItem(mContext.getResources().getText(R.string.host_release).toString());
                }
                tvText.setText(mContext.getResources().getText(R.string.meeting_setting_request_chair_pwd_note));
                confirmSettingTv.setText(mContext.getResources().getText(R.string.host_release));
                confirmSettingTv.setVisibility(View.VISIBLE);
                tvMecharTitle.setText(getTitle(true));
                tvText.setVisibility(View.VISIBLE);
                llPassword.setVisibility(View.GONE);
                setSaveBtnEnable(true);
            } else if (isHasChair) {
                // 会议中存在其他会场为主席，提示一下
                if (!isInit) {
                    updateParentItem(mContext.getResources().getText(R.string.host_claim).toString());
                }
                tvText.setVisibility(View.VISIBLE);
                String hostName = String.format(
                        mContext.getResources().getString(R.string.adv_host_other_chair_text),
                        ConfSdkPresenter.getHostName());
                tvText.setText("".equals(explain) ? hostName : explain);
                llPassword.setVisibility(View.GONE);
                setSaveBtnEnable(true);
                confirmSettingTv.setText(mContext.getResources().getText(R.string.host_claim));
                confirmSettingTv.setVisibility(View.GONE);
                tvMecharTitle.setText(getTitle(false));
            } else {
                // 会议中无主席方
                if (!isInit) {
                    updateParentItem(mContext.getResources().getText(R.string.host_claim).toString());
                }
                tvText.setText(TextUtils.isEmpty(explain) ? mContext.getResources().getText(
                        R.string.meeting_setting_no_chair_note) : explain);
                confirmSettingTv.setText(mContext.getResources().getText(R.string.host_claim));
                confirmSettingTv.setVisibility(View.VISIBLE);
                tvMecharTitle.setText(getTitle(false));
                llPassword.setVisibility(View.VISIBLE);
                setSaveBtnEnable(true);
                tvText.setVisibility(View.VISIBLE);
            }
        });
    }

    private CharSequence getTitle(boolean isMeChairman) {
        if (MeetingSettingDialog.EXTEND_MEETING_SETTINGS_VIEW.equals(fromView)) {
            return mContext.getText(R.string.extend_meeting);
        } else if (isMeChairman) {
            return mContext.getText(R.string.host_release);
        } else {
            return mContext.getText(R.string.host_claim);
        }
    }

    /**
     * 设置取消事件回调监听
     *
     * @param onDialogDismissEvent 事件回调监听
     */
    public void setOnDialogDismissEvent(Runnable onDialogDismissEvent) {
        this.onDialogDismissEvent = onDialogDismissEvent;
    }

    private void updateParentItem(String string) {
        if (onUpdateParentItemEvent != null) {
            onUpdateParentItemEvent.accept(string);
        }
    }

    /**
     * 设置更新MeetingSettingDialog中申请主席/释放主席item文字显示的事件回调监听
     *
     * @param updateParentViewItemEvent 事件回调监听
     */
    public void setUpdateParentViewItemEvent(Consumer<String> updateParentViewItemEvent) {
        this.onUpdateParentItemEvent = updateParentViewItemEvent;
    }

    @Override
    public void viewDataChanged(int eventId, Object obj) {
        LogUtil.info("viewDataChanged , eventId : " + eventId);
        if (eventId == ObserverConts.MSG_ATTENDESS_CHANGE_STATUS) {
            updateViewStatus(ConfSdkPresenter.isChairman(),
                    ConfSdkPresenter.isHasChairman(), false);
        }
    }

    @Override
    public void unRegisterListenService() {
        LogUtil.info("AdvApplyHostView unRegisterListenService");
        MeetingManager.getInstance().unregistDataChangeListenerObj(this);
    }

    @Override
    public void registerListenerService() {
        LogUtil.info("AdvApplyHostView registerListenerService");
        MeetingManager.getInstance().registerObserved(ObserverConts.MSG_ATTENDESS_CHANGE_STATUS, this);
    }

    @Override
    public void destroy() {
        unRegisterListenService();
        onUpdateParentItemEvent = null;
        super.destroy();
    }

    private void releaseHostChairDialog() {
        CustomFloatWindow mYesNoWindow = new CustomFloatWindow(mContext, DialogConst.RELEASE_CHAIR_DLG,
                mContext.getString(R.string.notice_relase_chair),
                mContext.getString(R.string.confirm), mContext.getString(R.string.cancel));
        mYesNoWindow.setBthHighLight(FloatWindowCustomBase.HIGH_LIGHT_OK);
        mYesNoWindow.showFloatWindow(10);
        mYesNoWindow.setCallBack(new CustomFloatWindow.OnBtnClickCallBack() {
            @Override
            public void isOkBtnClick() {
                LogUtil.info("A user try to release chair.");
                CustomFloatWindow.hideFloatWindow(DialogConst.RELEASE_CHAIR_DLG);
                releaseChairmanAuthority();
            }

            @Override
            public void isCancelBtnClick() {
                LogUtil.info("A user try to release chair but cancelled.");
                CustomFloatWindow.hideFloatWindow(DialogConst.RELEASE_CHAIR_DLG);
            }
        });
    }

    private void releaseChairmanAuthority() {
        ConfSdkPresenter.releaseChairmanAuthority(releaseChairCallback);
    }

    private MeetingCallback<Integer> releaseChairCallback = new MeetingCallback<Integer>() {
        @Override
        public void onSuccess(Integer succMsg) {
            LogUtil.info("releaseChairmanAuthority onSuccess");
            updateViewStatus(MeetingManager.getInstance().isMeChairman(),
                    MeetingManager.getInstance().isHasChairman(), false);
            updateToast(R.string.conf_control_message_relChair_success);
        }

        @Override
        public void onFailed(int errCode, String errMsg) {
            LogUtil.info("releaseChairmanAuthority onFailed");
            updateViewStatus(MeetingManager.getInstance().isMeChairman(),
                    MeetingManager.getInstance().isHasChairman(), false);
            updateToast(R.string.conf_control_message_relChair_failed);
        }
    };
}
